import {Injectable} from '@angular/core';
import {interval, Observable} from 'rxjs';
import {NgExServerConfigInterface} from 'ng-ex-tools';
import {take} from 'rxjs/operators';
import {TokenService} from './token.service';

export interface ServerConfig {
  name?: string;
  username?: string;
  password?: string;
  host: string;
  port: string;
  ssl: boolean;
}


@Injectable({
  providedIn: 'root'
})
export class ServerConfigService implements NgExServerConfigInterface {
  httpServer: string;
  webSocketServer: string;
  config: ServerConfig;
  ready = false;

  constructor(private tokenService: TokenService) {
    this.getConfig();
  }

  getServer(): Observable<any> {
    return new Observable((observe) => {
      const i = interval(10).pipe(take(300)).subscribe((num) => {
        if (this.ready) {
          i.unsubscribe();
          this.setServer();
          observe.next({httpServer: this.httpServer, webSocketServer: this.webSocketServer});
          observe.complete();
        }
        if (num === 299) {
          throw Error('配置读取失败');
        }
      });
    });
  }

  getConfig() {
    if (!this.config) {
      document.title = '九型人格测试';
      this.config = {
        host: localStorage.getItem('host') || window.location.hostname,
        port: localStorage.getItem('port') || window.location.port,
        ssl: localStorage.getItem('ssl') === 'true'
      };
    }
    const token = localStorage.getItem('token');
    this.tokenService.token = token ? token : '';
    this.ready = true;
  }

  setServer() {
    this.httpServer = `${this.config.ssl ? 'https' : 'http'}://${this.config.host}:${this.config.port}/api`;
    this.webSocketServer = `${this.config.ssl ? 'wss' : 'ws'}://${this.config.host}:${this.config.port}/websocket`;
  }

  setConfig(config: ServerConfig) {
    this.config.host = config.host;
    this.config.port = config.port;
    this.config.ssl = config.ssl;
    this.setServer();
  }
}
